package com.itheima.tlias.tliasweb.filter;

import com.alibaba.fastjson2.JSON;
import com.itheima.tlias.tliasweb.pojo.Result;
import com.itheima.tlias.tliasweb.util.JwtUtils;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Slf4j
//@WebFilter(urlPatterns = "/*")
public class LoginFilter implements Filter {
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest)request;
        HttpServletResponse res = (HttpServletResponse)response;
        log.info("----->LoginFilter doFilter， uri:{}", req.getRequestURI());
        // 获取请求路径
        String requestURI = req.getRequestURI();
        // 判断是否是登录请求
        if(requestURI.indexOf("/login")>=0){
            // 是登录
            chain.doFilter(request, response);
        }else{
            // 不是登录请求，需要验证token
            String token = req.getHeader("token");
            // token是空
            if(!StringUtils.hasLength(token)){
                // 返回失败
                res.setStatus(200);
                res.setContentType("application/json;charset=UTF8");
                PrintWriter writer = res.getWriter();
                Result result = Result.error("NOT_LOGIN");
                String json = JSON.toJSONString(result);
                writer.write(json);
            }else{
                // token存在
                try{
                    // 解析token
                    Claims claims = JwtUtils.parseJWT(token);
                    // 获取payload中的数据
                    Integer id = claims.get("id", Integer.class);
                    String username = claims.get("username", String.class);
                    if(id != null && StringUtils.hasLength(username)){
                        // token解析是成功的
                        chain.doFilter(request, response);
                    }else {
                        // token解析是失败的
                        res.setStatus(200);
                        res.setContentType("application/json;charset=UTF8");
                        PrintWriter writer = res.getWriter();
                        Result result = Result.error("NOT_LOGIN");
                        String json = JSON.toJSONString(result);
                        writer.write(json);
                    }
                }catch(Exception e){
                    log.error("token解析失败", e);
                    // token解析是失败的
                    res.setStatus(200);
                    res.setContentType("application/json;charset=UTF8");
                    PrintWriter writer = res.getWriter();
                    Result result = Result.error("NOT_LOGIN");
                    String json = JSON.toJSONString(result);
                    writer.write(json);
                }
            }
        }
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        log.info("LoginFilter init");
    }

    @Override
    public void destroy() {
        log.info("LoginFilter destroy");
    }
}
